package com.gitee.leijin.rbac.security.handler;

import cn.hutool.json.JSONUtil;
import com.gitee.leijin.rbac.util.AjaxUtils;
import com.gitee.leijin.rbac.util.Result;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.security.web.access.ExceptionTranslationFilter;
import org.springframework.stereotype.Component;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @see ExceptionTranslationFilter 出现 AccessDeniedException 并且不是匿名登录时 会回调
 *  源码见
 *  @see ExceptionTranslationFilter#handleAccessDeniedException
 *
 */
@Component
public class CustomAccessDeniedHandler implements AccessDeniedHandler {

    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {
        Result<String> loginResult = Result.failure("无访问权限");
        AjaxUtils.response(response, JSONUtil.toJsonStr(loginResult));
    }
}
